<?php

namespace core;

use core\lib\Route;

class Base
{
    public static $classMap = [];
    public $assign = [];

    public function __construct() {

    }

    /**
     * 调用控制器方法，执行返回结果
     * @throws \Exception
     */
    public static function run()
    {
        $route = new Route();
        $module = $route->module;
        $ctrl = $route->ctrl;
        $action = $route->action;
        //p($module, $ctrl, $action);
        $modulePath = $module ? '/' . $module : '';
        $ctrlFile = APP . $modulePath . '/ctrl/' . ucfirst($ctrl) . 'Ctrl.php';
        $moduleClass = $module ? '\\' . $module : '';
        $ctrlClass = '\\' . APP_MODULE . $moduleClass . '\ctrl\\' . ucfirst($ctrl) . 'Ctrl';
        //p($ctrlFile, $ctrlClass);
        if (is_file($ctrlFile)) {
            //include $ctrlFile;
            $ctrlObj = new $ctrlClass();
            $ctrlObj->$action();
        } else {
            throw new \Exception('控制器没找到: ' . $ctrlClass);
        }
    }

    /**
     * 自动加载文件
     * @param $className
     * @return bool
     */
    public static function load($className)
    {
        $className = str_replace('\\', '/', $className);
        if (isset(self::$classMap[$className])) {
            return true;
        }

        $filePath = ROOT . $className . '.php';
        //var_dump($className, $filePath);
        if (is_file($filePath)) {
            include $filePath;
            self::$classMap[$className] = $className;
        }
        return false;
    }

    /**
     * 前端赋值
     * @param $name
     * @param $value
     */
    public function assign($name, $value)
    {
        $this->assign[$name] = $value;
    }

    /**
     * 前端输出
     * @param $file
     */
    public function display($file)
    {
        $filePath = APP . '/views/' . $file;
        if (is_file($filePath)) {
            extract($this->assign);
            include $filePath;
        }
    }
}